package com.bstek.sample.redisSample;

import com.bstek.sample.domain.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 基于队列和线程的方式轮询消费订单
 * @author zxq
 * @version 1.0
 * @date
 */
@Service
@Slf4j
public class QueueTaskService {

    private volatile TaskInfo taskInfo = new TaskInfo();

    private static final   ExecutorService executorService = Executors.newSingleThreadExecutor();

    private static BlockingQueue<Order> tasks = new ArrayBlockingQueue<>(1024 * 1024);


    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i <10 ; i++) {
            int finalI = i;
            new Thread(()->{
                Order async = new Order(finalI,"订单");
                tasks.add(async);
            }).start();
        }


    }


    @PostConstruct
    public void init() {
        log.info("开始执行本地队列任务.......");
        executorService.submit(taskInfo);

    }
    public class TaskInfo implements Runnable {



        public  void addTask(Order order){
            tasks.offer(order);
        }

        @Override
        public void run() {
            log.info("开始执行任务，队列获取任务并且消费掉.....");
            for (; ; ) {
                try {
                    Order order = tasks.take();
                    log.info("从队列获取任务并获取到的订单对象...." + order.getOrderId());
                    if (order != null) {
                        log.info("开始消费日志.......");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }


    }
}
